package com.netdisk.dao.impl;

/**
 * 分组类
 * @author chenlong
 * 只有公司的管理员, 名字固定为root, 才能创建和修改用户组,
 *  
 *2013-4-13
 */
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;
import com.netdisk.dao.Dao;
import com.netdisk.entity.Group;

@Repository(value = "groupDao")
public class GroupDao extends Dao<Group> {

	@Override
	public void save(Group obj) {
		Session session = sessionFactory.getCurrentSession();
		session.save(obj);
	}

	@Override
	public void update(Group obj) {
		Session session = sessionFactory.getCurrentSession();
		session.update(obj);
	}

	@Override
	public void delete(Group obj) {
		Session session = sessionFactory.getCurrentSession();
		session.delete(obj);

	}

	@Override
	public List<Group> findAll() {
		Session session = sessionFactory.getCurrentSession();
		List<Group> groups = null;
		groups = session.createQuery("from Group").list();
		return groups;
	}

	@Override
	public Group findById(String id) {
		Session session = sessionFactory.getCurrentSession();
		List<Group> groups = null;
		Group group = null;
		Query query =  session.createQuery("from Group where id=:id");
		query.setString("id", id);
		groups =query.list();
		if (!groups.isEmpty()) {
			group = groups.get(0);
		}
		return group;
	}

	@Override
	public List<Group> findByTop(int from, int max) {
		Session session = sessionFactory.getCurrentSession();
		List<Group> groups = null;
		Query query = session.createQuery("from Group");
		query.setFirstResult(from);
		query.setMaxResults(max);
		groups = query.list();
		return groups;
	}

	/**
	 * 
	 * @param group
	 *            传入还没有持久化的group DTO, 通过companyId + groupName 判断是否组已经被 创建了
	 * @return true or false
	 */
	public boolean existWithGroupName(Group group) {
		Session session = sessionFactory.getCurrentSession();
		List<Group> groups = null;
		System.out.println("from Group where companyId = "
				+ group.getCompanyId() + " and " + "groupName = "
				+ group.getGroupName());
		Query query = session
				.createQuery("from Group where companyId=:companyId "
						+ "and groupName=:groupName");
		query.setString("companyId", group.getCompanyId());
		query.setString("groupName", group.getGroupName());
		groups = query.list();

		if (groups.isEmpty()) {
			return false;
		} else {
			return true;
		}
	}
}
